<template>
  <div>
    <div class="box">
      <div class="title" @click="toheader">喜马拉雅</div>
      <van-search v-model="value" shape="round" placeholder="搜索" @click="showBottom" />
      <van-button color="red" plain round size="small" @click="todownload">APP</van-button>
      <van-button color="red" plain round size="small" @click="tologin">登录</van-button>
      <van-popup v-model:show="show" position="bottom" :style="{ height: '100%' }">

        <div>
          <form action="/">
            <van-search v-model="value" show-action placeholder="请输入搜索关键词" @cancel="onCancel" @search="onSearchrecord"
              @update:model-value="onSearch" :autofocus="true" />
          </form>
          <!-- 历史记录 -->
          <div class="history" v-if="state.isShowHistory">
            <span class="proHot">搜索历史</span>
            <span class="delHotSearch" @click="delHostClick">清除历史</span>
          </div>
          <div class="searchBtn-div">
            <span v-for="(item, index) in state.historyList" :key="index" class="tag">{{ item }}</span>
          </div>
        </div>


        <van-tabs v-model:active="active" @click-tab="changeTab" v-show="isShow">
          <van-tab v-for="(item, index) in searchTabList" :key="index" :title="item.categoryName" @click="toDetail">

            <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" class="list">

              <van-cell v-for="(aaa, index) in searchList" :key="index" :title="index + 1" class="no"
                :class="{ active: index < 3 }">
                <span class="list-title">{{ aaa.word }}</span>
                <van-icon :name="aaa.shift == 1 ? 'down' : 'back-top'" :color="aaa.shift == 1 ? 'green' : 'red'" />
              </van-cell>

            </van-list>

            <van-back-top />
          </van-tab>
        </van-tabs>


        <div class="search">
          <div class="search-one" v-if="searchOneValue.length" v-for="item in searchOneValue" :key="item.id"
            @click="toDetail">
            <img class="one-img" :src="item.imgPath" alt="">
            <div class="one-context">
              <div class="one-title">{{ item.highlightKeyword }}</div>
              <div class="one-footer">
                <div class="text">{{ item.category }}</div>
                <div>{{ item.play / 10000 }} 万</div>
                <div>{{ item.tracks }} 集</div>
              </div>
            </div>
            <div class="icon"></div>
          </div>
          <div class="search-list" @click="toDetail">
            <div class="search-item" v-for="item in searchValue" :key="item.id">{{ item.keyword }}</div>
          </div>
        </div>





      </van-popup>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { getsearchlist, reqSearchList, reqkeywordList, getSearsh } from "../../api/search"
import { type searchlistModel, type SearchListModel, type QueryResultModel, type AlbumResultModel } from "../../api/search"
import router from '@/router';

const value = ref('');
const active = ref(0);
const show = ref(false);
const showBottom = () => {
  show.value = true;
};
const onCancel = () => {
  show.value = false
}


const toDetail = () => {
  router.push('/coursedetail')
}



const list = ref<number[]>([]);
const loading = ref(false);
const finished = ref(false);

const onLoad = () => {
  // 异步更新数据
  // setTimeout 仅做示例，真实场景中一般为 ajax 请求
  setTimeout(() => {
    for (let i = 0; i < 10; i++) {
      list.value.push(list.value.length + 1);
    }

    // 加载状态结束
    loading.value = false;

    // 数据全部加载完成
    if (list.value.length >= 40) {
      finished.value = true;
    }
  }, 1000);
};


//点击tab
const changeTab = async ({ name }: { name: number }) => {
  console.log(name)
  let categoryId = searchTabList.value[name].categoryId
  try {
    let result = await reqkeywordList(categoryId)
    // console.log(result);
    searchList.value = result.hotWordResultList
  } catch (error) {
    console.error(error)
  }
}


//获取搜索tab
const searchTabList = ref<searchlistModel[]>([])
const getSearchlist = async () => {
  try {
    let result = await getsearchlist()
    console.log(result);
    searchTabList.value = result.category
  } catch (error) {
    console.error(error)
  }
}

//获取搜索下拉列表
const categoryId = ref("-1")
const size = ref(24)
const searchList = ref<SearchListModel[]>([])
const resSearchList = async () => {
  try {
    let result = await reqSearchList(categoryId.value, size.value)
    // console.log(result);
    searchList.value = result.hotWordResultList
  } catch (error) {
    console.error(error)
  }
}

const isShow = ref(true)
//搜索框数据
const paidFilter = ref(false)
const scope = ref('all')
//搜索数据
const searchValue = ref<QueryResultModel[]>([])
const searchOneValue = ref<AlbumResultModel[]>([])
const onSearch = async () => {
  if (value.value) {
    isShow.value = false
    try {
      let res = await getSearsh(value.value, paidFilter.value, scope.value)
      console.log(res);
      searchValue.value = res.data.result.queryResultList
      searchOneValue.value = res.data.result.albumResultList
    } catch (error) {
      console.error(error)
    }
  } else {
    isShow.value = true
  }

}





// 历史记录
const state = ref<{
  isShowHistory: boolean, //是否显示历史记录
  value: string,  //搜索关键字
  historyList: string[]//历史
}>({
  isShowHistory: false, //是否显示历史记录
  value: '',  //搜索关键字
  historyList: []//历史搜索数据
})

const onSearchrecord = (val: string) => {
  // 搜索历史记录放进historyList
  state.value.historyList.push(val)
  value.value = ''
  if (state.value.historyList.length > 0) {
    state.value.isShowHistory = true
  } else {
    state.value.isShowHistory = false
  }
}
const delHostClick = () => {
  state.value.historyList = [] //历史搜索数据
  state.value.isShowHistory = false
}

// 跳转到首页
const toheader = () => {
  router.push('/homepage/tuijian')
  emit("back")
}

// 跳转到登录
const tologin =()=>{
  router.push('/login')
}


interface goBack {
  (abc: 'back'): void
}
const emit = defineEmits<goBack>()



// 跳转到下载页面
const todownload = () => {
  router.push('/download')
}


onMounted(() => {
  getSearchlist()
  resSearchList()
})
</script>

<style lang="less" scoped>
.box {
  width: 100%;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;

  .title {
    font-size: 12px;
    color: #f86442;
    font-weight: bold;
  }

  .open {
    width: 68px;
    height: 30px;
    font-size: 12px;
    padding: 8px 10px;
    border-color: #f86442;
    color: #f86442;
    border-radius: 10px;
  }
}

.list {
  width: 100%;

  .no {
    display: flex;

    &.active {
      color: #d75656;
      font-size: 20px;
    }


  }
}

.history {
  display: flex;
  justify-content: space-between;

  .proHot {
    font-size: 15%;
    padding-left: 2ch;
  }

  .deHotSearch {
    font-size: 15%;
    padding-left: 1ch;
  }
}

.searchBtn-div {
  .tag {
    height: 5px;
    width: 8px;
    border: 1px solid #aaa;
    color: #111;
    font-size: 4px;
    padding: 0 5px;
    margin: 0 10px;
    background-color: #eee;
  }
}

.search {
  width: 100%;

  .search-one {
    width: 90%;
    margin: 0 auto;
    display: flex;
    align-items: center;
    overflow: hidden;
    padding: 15px 0;
    border-bottom: 1px solid #ddd;
    justify-content: space-between;

    .one-img {
      width: 40px;
      height: 40px;
      border: none;
      font-size: 10px;
      border-radius: 5px;
      margin-right: 10px;
    }

    .one-context {
      width: 50%;
      flex: 1;

      .one-title {
        font-weight: 500;
        font-size: 14px;
        color: #40404c;
        padding-bottom: 4px;
        line-height: 20px;
      }

      .one-footer {
        display: flex;
        font-size: 12px;
        color: #a3a3ac;
        line-height: 16px;
        justify-content: space-between;
        width: 55%;

        .text {
          border: 1px solid #ccc;
          border-radius: 3px;
          text-align: center;
          height: 14px;
          padding: 0 4px;
        }
      }

    }

    .icon {
      width: 10px;
      height: 10px;
      background-color: #333;
    }
  }

  .search-list {
    width: 90%;
    margin: 0 auto;

    .search-item {
      line-height: 40px;
      font-size: 14px;
      color: #40404c;
      margin-left: 3px;
      border-bottom: 1px solid #ddd;
    }
  }
}
</style>